<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="8">
            <a-form-model-item label="检验单号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="reportNumber">
              <a-input v-model="model.reportNumber" disabled></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="检验标准" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="samplingQuantity">
              <j-search-select-tag
                placeholder="请选择检验标准"
                @change="handleInspectionStandardChange"
                v-model="model.standardId"
                :dict="inspectionStandardCode" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="抽检数量" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="samplingQuantity">
              <a-input-number v-model="model.samplingQuantity" placeholder="请输入抽检数量" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="检验日期" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="inspectionDate">
              <j-date placeholder="请选择检验日期" v-model="model.inspectionDate" style="width: 100%" />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
      <a-row>
          <a-col :span="24" >
            <j-vxe-table
              keep-source
              ref="qcReportInspectionItem"
              :loading="qcReportInspectionItemTable.loading"
              :columns="qcReportInspectionItemTable.columns"
              :dataSource="qcReportInspectionItemTable.dataSource"
              :maxHeight="300"
              :disabled="formDisabled"
              :rowNumber="true"
              :rowSelection="!formDisabled"
              :toolbar="true"
              :toolbarConfig="{
                slots: ['prefix', 'suffix'],
                btn: ['remove', 'clearSelection'],
              }"
              @remove="handleDelete"
            />
          </a-col>
      </a-row>
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="24">
            <a-form-model-item label="检验结果" :labelCol="labelCol2" :wrapperCol="wrapperCol2" prop="inspectionResult">
              <j-dict-select-tag type="radio" v-model="model.inspectionResult" dictCode="qc_inspection_result" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="备注" :labelCol="labelCol2" :wrapperCol="wrapperCol2" prop="remark">
              <a-input v-model="model.remark" placeholder="请输入备注" :disabled="formDisabled" />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>

import { getAction, postAction } from '@/api/manage'
import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin.js'
import { JVXETypes } from '@/components/jeecg/JVxeTable'
import { validateDuplicateValue } from '@/utils/util'
import JFormContainer from '@/components/jeecg/JFormContainer'
import dayjs from 'dayjs'

export default {
  name: 'QcReportForm',
  mixins: [JVxeTableModelMixin],
  components: {
    JFormContainer
  },
  data() {
    return {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      labelCol2: {
        xs: { span: 24 },
        sm: { span: 2 }
      },
      wrapperCol2: {
        xs: { span: 24 },
        sm: { span: 18 }
      },
      confirmLoading: false,
      model: {
        inspectionResult: 1,
        inspectionDate: dayjs().format('YYYY-MM-DD')
      },
      validatorRules: {},
      // 检验项目
      qcReportInspectionItemTable: {
        loading: false,
        dataSource: [],
        columns: [
          {
            title: '检验项目',
            key: 'itemName',
            type: JVXETypes.normal,
            minWidth: '200px'
          },
          {
            title: '上限值',
            key: 'upperLimit',
              type: JVXETypes.normal,
            width:"200px",
            defaultValue:'',
          },
          {
            title: '标准值',
            key: 'qualityStandard',
            type: JVXETypes.normal,
            width: '200px'
          },
          {
            title: '下限值',
            key: 'lowerLimit',
              type: JVXETypes.normal,
            width:"200px",
            defaultValue:'',
          },
          {
            title: '结果录入',
            key: 'result',
            type: JVXETypes.inputNumber,
            placeholder: '请输入${title}',
            defaultValue: '',
            width:"200px",
            validateRules: [{ required: true, message: '${title}不能为空' }]
          },
          {
            title: '备注',
            key: 'remark',
            type: JVXETypes.normal,
            minWidth:"200px",
            defaultValue:'',
          },
        ]
      },
      url: {
        edit: '/qms/inspection/report/edit',
        queryById: '/qms/inspection/report/queryById',
        qcReportInspectionItem: {
          list: '/qms/inspection/report/queryQcReportInspectionItemByMainId'
        },
        rawMaterialInspectionStandardItem: {
          list: '/qc/eneQcMaterialsCheck/queryEneQcMaterialsCheckDetailByMainId'
        },
        packagingMaterialInspectionStandardItem: {
          list: '/packagecheck/enePackageCheck/queryEnePackageCheckDetailByMainId'
        },
        finishedProductFinalInspectionStandardItem: {
          list: '/eneinspectioncheck/eneInspectionCheck/queryEneInspectionCheckDetailByMainId'
        },
        commonCheckStandardItem: {
          list: '/commoncheck/eneCommonCheck/queryEneCommonCheckDetailByMainId'
        }
      }
    }
  },
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    },
    reportType: {
      type: String,
      required: true
    }
  },
  computed: {
    formDisabled() {
      return this.disabled
    },
    inspectionStandardCode() {
      if (this.reportType === 'raw-material') {
        return 'ene_qc_materials_check,check_standard,id'
      } else if (this.reportType === 'packaging-material') {
        return 'ene_package_check,check_standard,id'
      } else if (this.reportType === 'finished-product-final') {
        return 'ene_inspection_check,check_standard,id'
      } else if (this.reportType === 'hardware') {
        return 'ene_common_check,check_standard,id'
      }
      return ''
    },
    inspectionStandardItemUrl() {
      if (this.reportType === 'raw-material') {
        return this.url.rawMaterialInspectionStandardItem.list
      } else if (this.reportType === 'packaging-material') {
        return this.url.packagingMaterialInspectionStandardItem.list
      } else if (this.reportType === 'finished-product-final') {
        return this.url.finishedProductFinalInspectionStandardItem.list
      } else if (this.reportType === 'hardware') {
        return this.url.commonCheckStandardItem.list
      }
      return ''
    }
  },
  created() {
  },
  methods: {
    edit(record) {
      this.model = Object.assign({}, record)
      this.model.inspectionResult = '1'
      this.model.inspectionDate = dayjs().format('YYYY-MM-DD')
      this.qcReportInspectionItemTable.dataSource = []
    },
    async handleSubmit() {
      const validate = await this.$refs.form.validate()
      if (!validate) {
        return
      }
      if (this.reportType !== 'hardware') {
        const errMap = await this.$refs.qcReportInspectionItem.validateTable()
        if (errMap) {
          return
        }
      }
      const formData = {
        id: this.model.id,
        standardId: this.model.standardId,
        samplingQuantity: this.model.samplingQuantity,
        inspectionResult: this.model.inspectionResult,
        inspectionDate: this.model.inspectionDate,
        remark: this.model.remark,
        qcReportInspectionItemList: this.qcReportInspectionItemTable.dataSource.map(item => {
          return {
            ...item,
            id: null
          }
        })
      }
      this.request(formData)
    },
    request(formData) {
      this.confirmLoading = true
      postAction(this.url.edit, formData)
        .then((res) => {
          if (res.success) {
            this.$message.success('保存成功')
            this.$emit('ok')
            this.close()
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          this.confirmLoading = false
        })
    },
    detail(record) {
      this.model = Object.assign({}, record)
      this.qcReportInspectionItemTable.dataSource = []
      this.$nextTick(() => {
      })
      // 加载子表数据
      if (this.model.id) {
        let params = { id: this.model.id }
        this.requestSubTableData(this.url.qcReportInspectionItem.list, params, this.qcReportInspectionItemTable)
      }
    },
    validateError(msg) {
      this.$message.error(msg)
    },
    handleInspectionStandardChange(value) {
      const params = { id: value }
      getAction(this.inspectionStandardItemUrl, params).then(res => {
        let { result } = res
        if (result) {
          this.qcReportInspectionItemTable.dataSource = result.map(item => {
            return {
              inspectionStandardId: item.pid || item.packageId || item.inspectionId || item.commonId,
              itemName: item.analyseItem,
              qualityStandard: item.qualityIndex,
              upperLimit: item.upperLimit,
              lowerLimit: item.lowerLimit,
              remark: item.remark,
              result: ''
            }
          })
        }
      })
    },
    handleDelete({ deleteRows }) {
      this.qcReportInspectionItemTable.dataSource = this.qcReportInspectionItemTable.dataSource.filter(row =>
        !deleteRows.some(item => item.id === row.id)
      )
    }
  }
}
</script>

<style scoped>
</style>